package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.util.JsonResult;
import cn.wolfcode.rbac.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.security.provider.MD5;

import javax.swing.text.html.parser.Entity;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IPermissionService permissionService;//登录需要告知系统，用户的权限是啥
    @Override
    @Transactional(readOnly = true)
    public void login(String username, String password) {
        Employee employee = this.employeeMapper.selectByInfo(username,password);
        if(employee == null){
            throw new RuntimeException("用户名或密码错误");
        }

        UserContext.setCurrentUser(employee);
        List<String> permissions = this.permissionService.selectByEmpId(employee.getId());
        UserContext.setExpression(permissions);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo query(QueryObject qo) {
        //分页的总条数
//        Integer rows = this.employeeMapper.selectForCount(qo);
//        if(rows.intValue() == 0){
//            return new PageResult(Integer.valueOf(qo.getPageSize()));
//        }
        //分页的每页记录
//        List<Employee> list = this.employeeMapper.selectForList(qo);
//        return new PageResult(Integer.valueOf(qo.getCurrentPage()),rows,list,Integer.valueOf(qo.getPageSize()));
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> list = this.employeeMapper.selectForList(qo);
        return new PageInfo(list);
    }
    //ids对修改角色使用的，保存角色信息的
    @Override
    public void saveOrUpdate(Employee paramEmployee, Long[] ids) {
        //判断一下是更新还是修改
        if(paramEmployee.getId() == null){
            String password = paramEmployee.getPassword();
            Md5Hash md5Hash = new Md5Hash(password,paramEmployee.getName());
            //Md5Hash md5Hash = new Md5Hash(password);
            paramEmployee.setPassword(md5Hash.toString());
            this.employeeMapper.insert(paramEmployee);
        }else{
            this.employeeMapper.updateByPrimaryKey(paramEmployee);
            //在更新的同时现将原来的角色删除掉，再重新添加角色信息
            this.employeeMapper.deleteRelation(paramEmployee.getId());
        }
//        //对角色修改
        if((ids != null) && (ids.length > 0)){
            for (Long roleId : ids){
                this.employeeMapper.insertRelation(paramEmployee.getId(),roleId);
           }
        }
    }

    @Override
    public void delete(Long paramLong) {
        this.employeeMapper.deleteByPrimaryKey(paramLong);
        //删除员工对应的关联表中的数据
        this.employeeMapper.deleteRelation(paramLong);
    }

    @Override
    @Transactional(readOnly = true)
    public Employee get(Long paramLong) {
        return this.employeeMapper.selectByPrimaryKey(paramLong);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Employee> list() {
        return this.employeeMapper.selectAll();
    }

    @Override
    public void abtchDelete(Long[] ids) {
        this.employeeMapper.deleteBbatch(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return this.employeeMapper.get(name);
    }

    @Override
    public Workbook exportxls() {
        //创建一个Excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet（Excel文件工作簿） 给sheet起名和不起名的实现
        Sheet sheet = wb.createSheet("员工名单");
        //创建行，从0开始
        Row row = sheet.createRow(0);
        // 单元格 写表头信息
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> list = employeeMapper.selectAllForList();
        for(int i = 0;i<list.size();i++){
            Employee employee = list.get(i);
            //创建行
            row = sheet.createRow(i+1);
            //System.out.println(employee);
            //设置单元格的内容
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        //创建列，创建行和列实际就是创建单元格，
        //Cell cell = row.createCell(0);
        //设置内容到单元格内
       // cell.setCellValue("worfcode");
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        InputStream stream = file.getInputStream();
        //读取接收到的模板文件xls并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取sheet页
        Sheet sheet = wb.getSheetAt(0);
        //先获取总的总行数（索引号），索引从0开始
        int lastRowNum = sheet.getLastRowNum();
        System.out.println(lastRowNum);
        //从索引为1的行数开始取数，循环要从1开始
        for(int i = 1;i<=lastRowNum;i++){
            Row row = sheet.getRow(i);
            Employee employee = new Employee();
            //getxxxCellValue()要与xls单元格的类型保持一致
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            employee.setAge((int)row.getCell(2).getNumericCellValue());
            System.out.println(employee);
            Md5Hash md5 = new Md5Hash(row.getCell(0).getStringCellValue());
            employee.setPassword("1");
            //保存到数据库
            this.saveOrUpdate(employee,null);
        }
    }
}
